#!/bin/bash

# 集群路径
CLUSTER_PATH=/home/wangke/apps/demo-springcloud-2/demo-springcloud-2-gateway

# 集群节点
NODE_NAME=node1

# 节点路径
NODE_PATH=$CLUSTER_PATH/$NODE_NAME

# Jar包名称
APP_JAR=demo-springcloud-2-gateway-0.0.1-SNAPSHOT.jar

# 日志路径
LOG_PATH=$NODE_PATH/logs/all.log

# JVM参数
JVM_OPTS="-Duser.timezone=Asia/Shanghai -Xms128M -Xmx128M -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=$NODE_PATH/logs"

# 端口参数
PORT=10301

# Profile参数
PROFILE=pro

# 注册中心地址
SERVICE_URL=http://node4:8761/eureka/,http://node5:8762/eureka/

if [ "$1" = "" ];
then
    echo -e "\033[0;31m 未输入操作名 \033[0m  \033[0;34m {start|stop|restart|status} \033[0m"
    exit 1
fi

function start()
{
    PID=`ps -ef |grep java|grep $APP_JAR|grep $NODE_NAME|grep -v grep|awk '{print $2}'`

	if [ x"$PID" != x"" ]; then
	    echo "$APP_JAR is running..."
	else
        nohup java -jar $JVM_OPTS $NODE_PATH/lib/$APP_JAR --server.port=$PORT --spring.profiles.active=$PROFILE --eureka.client.service-url.defaultZone=$SERVICE_URL > $LOG_PATH 2>&1 &
        echo "Start $APP_JAR success..."
	fi
}

function stop()
{
    echo "Stop $APP_JAR"

	PID=""
	query() {
		PID=`ps -fu $username |grep java|grep $APP_JAR|grep $NODE_NAME|grep -v grep|awk '{print $2}'`
	}

	query
	if [ x"$PID" != x"" ]; then
		kill -TERM $PID
		echo "$APP_JAR (pid:$PID) exiting..."
		while [ x"$PID" != x"" ]
		do
			sleep 1
			query
		done
		echo "$APP_JAR exited."
	else
		echo "$APP_JAR already stopped."
	fi
}

function restart()
{
    stop
    sleep 2
    start
}

function status()
{
    PID=`ps -fu $username |grep java|grep $APP_JAR|grep $NODE_NAME|grep -v grep|awk '{print $2}'`
    if [ x"$PID" != x"" ];then
        echo "$APP_JAR is running..."
    else
        echo "$APP_JAR is not running..."
    fi
}

case $1 in
    start)
    start;;
    stop)
    stop;;
    restart)
    restart;;
    status)
    status;;
    *)

esac